package pl.freetimetool.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import pl.freetimetool.domain.Account;
import pl.freetimetool.domain.AccountRole;
import pl.freetimetool.exceptions.UserNotFoundException;

public class AccountDaoImpl implements AccountDao {

	@PersistenceContext
	EntityManager entityManager;

	public Account findUsername(final String username) throws UserNotFoundException {
		final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
		final CriteriaQuery<Account> c = cb.createQuery(Account.class);
		final Root<Account> r = c.from(Account.class);
		try {
			c.select(r).where(cb.equal(r.get("username"), username));
			return this.entityManager.createQuery(c).getSingleResult();
		} catch (final NoResultException nre) {
			throw new UserNotFoundException();
		} catch (final IllegalArgumentException iae) {
			throw new UserNotFoundException();
		}
	}

	public void save(final Account account) {
		this.entityManager.persist(account);
	}

	public Collection<Account> listAccounts(final Collection<AccountRole> roles) {
		final List<String> c = new ArrayList<String>(roles.size());
		for (final AccountRole in : roles) {
			c.add(in.getRole());
		}
		final List<Account> accounts = this.entityManager.createQuery("SELECT a FROM Account a JOIN a.accountRole r WHERE r.role IN(?1)", Account.class)
				.setParameter(1, c).getResultList();
		return accounts;
	}

	public void remove(final Account account) {
		this.entityManager.remove(account);
	}

}
